package com.example.controller;

import com.example.models.MyDTO;
import com.example.util.JsonUtil;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Date 2021/6/27
 * @Created by Jonathan
 */
//@Component
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class SocketForHttpGetRequest implements ApplicationRunner {
    private int port = 30000;
    //    private int port = 8080;
    private String host = "localhost";
    private Socket socket;
    private BufferedReader bufferedReader;
    private BufferedWriter bufferedWriter;


    public void sendGet() throws IOException {
        MyDTO dto = new MyDTO("zhangsan", "password");
        String s = JsonUtil.pojoToJson(dto);
        String requestUrlPath = "/get/body/" + new Random().nextInt(10000);
        log.info("url:{}", requestUrlPath);
        OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream());
        bufferedWriter = new BufferedWriter(streamWriter);
        bufferedWriter.write("GET " + requestUrlPath + " HTTP/1.1\r\n");
        bufferedWriter.write("Content-Type: application/json\r\n");
        bufferedWriter.write("Accept: */*\r\n");
        bufferedWriter.write("Accept-Encoding: gzip, deflate, br\r\n");
        bufferedWriter.write("Host: " + this.host + "\r\n");
        bufferedWriter.write("Content-Length: 57\r\n");
        bufferedWriter.write("\r\n"); // 换行头部结束
//        bufferedWriter.flush();
        bufferedWriter.write(s);
        bufferedWriter.flush();
        BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream());
        bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8"));
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            log.info("line:{}", line);
        }
        bufferedReader.close();
        bufferedWriter.close();
        socket.close();

    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // https协议
        socket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(this.host, this.port);
//        socket = new Socket(this.host, this.port);
        TimeUnit.SECONDS.sleep(6);
        sendGet();

    }

    public static void main(String[] args) {

    }
}
